<template>
  <t-tabs v-if="cacheStore.tagList.length > 0" v-model="activePage" @change="changePage" @remove="removeTab"
          @contextmenu.prevent="$event.preventDefault()">
    <t-tab-panel v-for="(item, index) in cacheStore.tagList" :key="item.name" :value="item.fullPath" removable>
      <template #label>
        <t-dropdown :min-column-width="88" trigger="context-menu" :popup-props="{
              overlayClassName: 'route-tabs-dropdown'
            }">
          <t-space>
            <t-icon v-if="item.icon" :name="item.icon" :style="{color: item.iconColor}"/>
            {{ item.title }}
          </t-space>
          <t-dropdown-menu>
            <t-dropdown-item v-if="index > 0" @click="removeLeft(index)"><t-icon name="arrow-left" />关闭左边</t-dropdown-item>
            <t-dropdown-item v-if="index < cacheStore.tagList.length - 1" @click="removeRight(index)"><t-icon name="arrow-right" />关闭右边</t-dropdown-item>
            <t-dropdown-item @click="removeOther(index)"><t-icon name="close-circle" />关闭其他</t-dropdown-item>
            <t-dropdown-item @click="removeAll"><t-icon name="close-circle" style="color: red"/>关闭所有</t-dropdown-item>
          </t-dropdown-menu>
        </t-dropdown>
      </template>
    </t-tab-panel>
  </t-tabs>
  <div style="flex:1; overflow: auto; padding:16px;">
    <router-view v-slot="{ Component }">
      <transition name="fade-transform" mode="out-in">
        <keep-alive :include="cacheTagName">
          <component :is="Component"/>
        </keep-alive>
      </transition>
    </router-view>
  </div>
</template>

<script setup lang="ts">
import {computed, onMounted, ref, watch} from "vue";
import {useCacheStore} from "@/store/modules/cache";
import {type RouteLocationNormalizedLoaded, useRoute, useRouter} from "vue-router";
import type {TabsProps} from "tdesign-vue-next";
import type {RouteItem} from "@/typings/auth";

const cacheStore = useCacheStore();

const cacheTagName = computed(() => cacheStore.tagList.map(item => item.name));

const route = useRoute();
const router = useRouter();
const activePage = ref('');
const activeIndex = ref(0);

const createTag = (route: RouteLocationNormalizedLoaded): RouteItem => {
  return {
    fullPath: route.fullPath,
    name: String(route.name ?? ""),
    title: route.meta?.title ?? "",
    icon: route.meta?.icon,
    iconColor: route.meta?.iconColor
  };
};

const setTag = (route: RouteLocationNormalizedLoaded) => {
  const tagList = cacheStore.tagList;

  // 使用 Map 提高查找效率
  const tagMap = new Map<string, number>();
  tagList.forEach((item, index) => {
    tagMap.set(item.fullPath, index);
  });

  if (tagList.length === 0 || !tagMap.has(route.fullPath)) {
    const newTag = createTag(route);
    tagList.push(newTag);
    activeIndex.value = tagList.length - 1;
  } else {
    activeIndex.value = tagMap.get(route.fullPath) ?? 0;
  }

  // 校验 fullPath 是否有效
  if (route.fullPath) {
    activePage.value = route.fullPath;
  } else {
    console.warn("Invalid fullPath in route:", route);
  }
}

const changePage = (value: string) => {
  router.push(value)
}

const removeTab: TabsProps['onRemove'] = ({value: val, index}) => {
  if (index < 0) return false;
  cacheStore.tagList.splice(index, 1);
  if (cacheStore.tagList.length === 0) {
    router.push("/");
    return
  }
  if (activePage.value === val) {
    activePage.value = cacheStore.tagList[Math.max(index - 1, 0)].fullPath;
    router.push(activePage.value);
  }
};

const removeLeft = (index: number) => {
  const item = cacheStore.tagList[index];
  // 使用 slice 方法截取数组，避免不必要的遍历
  const startIndex = Math.min(index, cacheStore.tagList.length);
  cacheStore.tagList = cacheStore.tagList.slice(startIndex);
  router.push(item.fullPath);
}

const removeRight = (index: number) => {
  const item = cacheStore.tagList[index];
  // 确保 activeIndex.value 在合理范围内
  const validIndex = Math.max(0, Math.min(index, cacheStore.tagList.length - 1));
  // 使用 slice 方法高效截取数组
  cacheStore.tagList = cacheStore.tagList.slice(0, validIndex + 1);
  router.push(item.fullPath);
}

const removeOther = (index: number) => {
  const item = cacheStore.tagList[index];
  cacheStore.tagList = [item];
  activePage.value = item.fullPath;
  router.push(activePage.value);
}

const removeAll = () => {
  cacheStore.tagList = [];
  activePage.value = '/';
  router.push('/');
}

onMounted(() => {
  if (route.fullPath !== "/") {
    setTag(route);
  } else {
    const tagList = cacheStore.tagList;
    if (tagList.length > 0) {
      router.push(tagList[0].fullPath)
    }
  }
})

watch(() => route.fullPath, () => {
  if (route.fullPath !== "/") {
    setTag(route);
  }
})
</script>

<style scoped lang="scss">
.tabs-icon-margin {
  margin-right: 8px;
}

.route-tabs-dropdown {
  .t-icon {
    margin-right: 8px;
  }
}
</style>